(function() {
	//初始化array,添加indexOf方法
	if(!window.Array.indexOf) {
		window.Array.prototype.indexOf = function(obj) {
			for(var i = 0; i < this.length; i++) {
				if(this[i] == obj) {
					return i;
				}
			}
			return -1;
		}
	} else {
		window.Array.prototype.remove = function(val) {
			if(this.indexOf(val) > -1) {
				this.splice(index, 1);
			}
		};
	}
	/**************************************业务部分START****************************************/

	window.chatUtils = {
		//本人信息
		userInfo: {
			name: '',
			nickname: '',
			password: '123456'
		},

		//登录功能
		loginIM: function(username, loginTime) {
			if(username && jQuery.trim(username) != '') {
				var loginTime = loginTime ? loginTime : 0;
				var options = {
					apiUrl: WebIM.config.apiURL,
					user: username,
					pwd: '123456',
					appKey: WebIM.config.appkey,
					success: function(data) {
						//登录成功
						var user = data.user;
						chatUtils.userInfo.name = user.username;
					},
					error: function(data) {
						//登录失败
						if(loginTime < 4) {
							chatUtils.loginIM(username, ++loginTime)
						} else {
							chatUtils.registe(username, 1);
						}
					}
				};
				conn.open(options);
			}
		},

		/*注册接口 START*/
		registe: function(username, regiTime) {
			if(username && jQuery.trim(username) != '') {
				conn.registerUser({
					username: username,
					password: '123456',
					nickname: 'nickname',
					appKey: WebIM.config.appkey,
					success: function() {
						chatUtils.loginIM(username);
					},
					error: function() {
						if(regiTime == undefined || regiTime < 3) {
							regiTime ? regiTime++ : 1;
							chatUtils.registe(username, regiTime);
						} else {
							alert('注册失败');
						}
					},
					apiUrl: WebIM.config.apiURL
				});
			} else {
				console.log('用户名为空');
			}
		},

		//登出功能
		loginOut: function() {
			conn.close();
		}

	}

	/****************************************************系统入口*****************************************************/
	//获取即将用来登录的用户名

	window.conn = new WebIM.connection({
		https: WebIM.config.https,
		url: WebIM.config.xmppURL,
		isAutoLogin: WebIM.config.isAutoLogin,
		isMultiLoginSessions: WebIM.config.isMultiLoginSessions
	});
	conn.listen({
		//登录后初始化
		onOpened: function(message) {
			//对客服发起视屏请求客服帐号写死
			/*rtcCall.caller = chatUtils.userInfo.name;
			rtcCall.makeVideoCall(13929563939);*/
		},
		onClosed: function(message) {
			chatUtils.loginIM(chatUtils.userInfo.name, 3);
		}, //连接关闭回调
		onTextMessage: function(message) {}, //收到文本消息
		onEmojiMessage: function(message) {}, //收到表情消息
		onPictureMessage: function(message) {}, //收到图片消息
		onCmdMessage: function(message) {}, //收到命令消息
		onAudioMessage: function(message) {}, //收到音频消息
		onLocationMessage: function(message) {}, //收到位置消息
		onFileMessage: function(message) {}, //收到文件消息
		onVideoMessage: function(message) {}, //收到视频消息
		onPresence: function(e) {}, //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
		onRoster: function(message) {}, //处理好友申请
		onInviteMessage: function(message) {}, //处理群组邀请
		onOnline: function() {}, //本机网络连接成功
		onOffline: function() {}, //本机网络掉线
		onError: function(message) {}, //失败回调
		onBlacklistUpdate: function(list) {}
	});
	/*初始化实时通话*/
	window.rtcCall = new WebIM.WebRTC.Call({
		connection: conn,
		mediaStreamConstaints: {
			audio: true,
			video: true
		},
		listener: {
			onAcceptCall: function(from, options) {
				console.log('链接成功!')
				console.log('onAcceptCall::', 'from: ', from, 'options: ', options);
			},
			//通过streamType区分视频流和音频流，streamType: 'VOICE'(音频流)，'VIDEO'(视频流)
			//获取远程连接
			onGotRemoteStream: function(stream, streamType) {
				var eleBox = document.getElementById('videobox');
				$('#video').show();
				console.log('onGotRemoteStream::', 'stream: ', stream, 'streamType: ', streamType);
				var video = document.getElementById('video');
				video.srcObject = stream;
				//$('#cancelCall').hide();

				if(stream && stream.active == true) {
					//与客服成功接通开始咨询
					document.removeEventListener("listen", oneTurnCall, false);
				}

			},
			//获取本地连接
			onGotLocalStream: function(stream, streamType) {
				//$('#cancelCall').show();
				console.log('onGotLocalStream::', 'stream:', stream, 'streamType: ', streamType);
				var eleBox = document.getElementById('localVideo');
				eleBox.srcObject = stream;
			},
			//正在呼叫
			onRinging: function(caller) {
				console.log('onRinging::', 'caller:', caller);
			},
			//挂断
			onTermCall: function(reason) {
				console.log('onTermCall::');
				console.log('reason:', reason);
				if(reason == 'decline') {
					//对方拒接
					document.dispatchEvent(ev);
					console.log('对方已拒绝');
				}
				if(reason == 'busy') {
					document.dispatchEvent(ev);
					console.log('对方正忙,请稍后重播');
				}
			},
			//状态改变
			onIceConnectionStateChange: function(iceState) {
				if(iceState == 'closed') {
					setTimeout(function() {
						$('#videobox,.callBox').remove();
					}, 1000)
					console.log('视屏关闭');
				}
				console.log(iceState);
			},
			onError: function(e) {
				$('#videobox').remove();
				if(e.message && e.message.indexOf('not online') >= 0) {
					//对方不在线
					console.log(e);
					document.dispatchEvent(ev);
				} else {
					alert('联接错误,请检查您的视频/音频设备');
				}
			}
		}
	});

/*	$(document).on('click', '.closeVideo,', function() {
		rtcCall.endCall();
		setTimeout(function() {
			$('#videobox').remove();
		}, 500);
	}).on('click', '.videoButton', function() {
		var to = $.trim($('.chatshow').data('name'));
		if(to != undefined && to != '' && to != chatUtils.userInfo.name) {
			rtcCall.caller = chatUtils.userInfo.name;
			rtcCall.makeVideoCall(to);
		}
	});*/

	//自定义事件
	var ev = document.createEvent('HTMLEvents');
	ev.initEvent('listen', false, false);　　
	document.addEventListener("listen", function() {
		//do something
	}, false);

}());

window.onload = function() {
	//获取一个可用的终端帐号
	function getOneCountForLogin() {
		var totalList = [];
		var result = new Promise(function(resolve, reject) {
			loginCount(resolve, reject);
		});

		function loginCount(reso, reje) {
			var countList = randNum(357, 550);
			if(!countList) {
				reje('没有空闲聊天帐号可使用,请稍后');
				alert('没有空闲聊天帐号可使用,请稍后');
			} else {
				getOneCount(countsOnlineResu(countList), reso, reje);
			}
		}
		//查询此帐号是否在线
		function searchIfOnline(count) {
			var promi = new Promise(function(resolve, reject) {
				$.ajax({
					type: "GET",
					url: "/huanxin/getUserMode",
					data: {
						tel: 'terminal' + count
					},
					dataType: "json",
					success: function(data) {
						if(data.data_map != null && data.data_map.hasOwnProperty('terminal' + count) && data.data_map['terminal' + count] == 'offline') {
							reject(count);
						} else {
							resolve(true);
						}
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						resolve(false);
					}
				});
			});
			return promi;
		}
		//获取一波查询对象
		function countsOnlineResu(countList) {
			var promisList = [];
			for(var i = 0; i < countList.length; i++) {
				promisList.push(searchIfOnline(countList[i]));
			}
			return promisList;
		}
		//判断这波查询结果
		function getOneCount(promisList, reso, reje) {
			Promise.all(promisList).then(function(e) {
				//如果账户全部在线,则重新搜索
				loginCount(reso, reje);
			}, function(e) {
				//如果有帐号不在线resolve账户名
				reso(e);
				console.log('账户 ' + e + '可用');
			});
		}
		//获取5个随机帐号
		function randNum(minnum, maxnum) {
			var box = 0;
			var numList = [];
			var arryLen = (maxnum - minnum + 1) - totalList.length;
			if(arryLen < 1) {
				return false;
			}
			if(arryLen < 5) {
				while(numList.length < arryLen) {
					box = getOneNum(minnum, maxnum);
					if(totalList.indexOf(box) < 0 && numList.indexOf(box) < 0) {
						numList.push(box);
					}
				}
			} else {
				while(numList.length < 5) {
					box = getOneNum(minnum, maxnum);
					if(totalList.indexOf(box) < 0 && numList.indexOf(box) < 0) {
						numList.push(box);
					}
				}
			}

			function getOneNum(minnum, maxnum) {
				return Math.floor(minnum + Math.random() * (maxnum - minnum + 1));
			}
			totalList = totalList.concat(numList);
			return numList;
		}
		return result;
	}

	//获取所有在线客服的帐号
	window.getOneServerForChat=function() {

		var turnInfo = {
			list: [],
			items: []
		};

		function searchIfOnline(count) {
			var promi = new Promise(function(resolve, reject) {
				$.ajax({
					type: "GET",
					url: "/huanxin/getUserMode",
					data: {
						tel: 'CustomerService' + count
					},
					dataType: "json",
					success: function(data) {
						if(data.data_map != null && data.data_map.hasOwnProperty('CustomerService' +
								count) && data.data_map['CustomerService' + count] == 'online') {
							resolve(count);
						} else {
							resolve(false);
						}
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						resolve(false);
					}
				});
			});
			return promi;
		}

		function getStatues(num) {
			var statues = [];
			for(var k = 0; k <= num; k++) {
				statues.push(searchIfOnline(k));
			}
			console.log(statues);
			return statues;
		}

		//0-21
		function doCallServer() {
			var getOnlineList = new Promise(function(resolve, reject) {
				Promise.all(getStatues(21)).then(function(e) {
					var onlineList = [];
					for(var l = 0; l < e.length; l++) {
						if(e[l] || e[l] === 0 || e[l] === '0') {
							onlineList.push(e[l]);
						}
					}
					if(onlineList.length > 0) {
						resolve(onlineList);
					} else {
						reject(false);
					}

				});
			});

			getOnlineList.then(function(e) {
				turnInfo.list = e;
				turnInfo.items = [];
				oneTurnCall();
			}, function(e) {
				alert('没有在线的客服,请于工作日拨打');
			});
		}

		window.oneTurnCall = function() {
			if(turnInfo.items.length >= turnInfo.list.length) {
				
				$('.askhelp').trigger('click');
				
				alert('没有在线的客服,请稍后再拨');
				return;
			}
			var server = getOneNum(0, 21);
			if(turnInfo.list.indexOf(server) >= 0 && turnInfo.items.indexOf(server) < 0) {
				turnInfo.items.push(server);
				if(!turnInfo.items.length || turnInfo.items.length <= 0) {
					alert('没有在线的客服,请稍后再拨');
				} else {
					rtcCall.caller = chatUtils.userInfo.name;
					rtcCall.makeVideoCall('CustomerService' + turnInfo.items[(turnInfo.items.length < 1 ? 0 : turnInfo.items.length - 1)]);
					console.log(chatUtils.userInfo.name);
					console.log('CustomerService' + turnInfo.items[(turnInfo.items.length < 1 ? 0 : turnInfo.items.length - 1)]);
				}
			} else {
				oneTurnCall();
			}

			function getOneNum(minnum, maxnum) {
				return Math.floor(minnum + Math.random() * (maxnum - minnum + 1));
			}
		}

		//自定义事件用来继续客服轮询请求
		window.ev = document.createEvent('HTMLEvents');
		ev.initEvent('listen', false, false);　　
		document.addEventListener("listen", oneTurnCall, false);

		doCallServer();
	}

	//getOneServerForChat();

	//setTimeout(getOneServerForChat, 2000);

	//获取一个空闲帐号
	getOneCountForLogin().then(function(e) {
		console.log(e);
		loginIm('terminal' + e)
	}, function() {
		alert('没有空闲帐号');
	});

	window.loginIm = function(username, loginTime) {
		var options = {
			apiUrl: WebIM.config.apiURL,
			user: username,
			pwd: '123456',
			appKey: WebIM.config.appkey,
			success: function(data) {
				//登录成功
				var user = data.user;
				chatUtils.userInfo.name = user.username;
			},
			error: function(data) {
				//登录失败
				if(loginTime > 1) {
					setTimeout(loginIm, 400, username, --loginTime);
				} else {
					alert('登录失败');
				}
			}
		};
		conn.open(options);
	};

};